package com.bci.pwtz.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.mysql.model.Dydl;
import com.bci.pwtz.mysql.model.Dydlfjx;
import com.bci.pwtz.mysql.model.Dygt;
import com.bci.pwtz.mysql.model.Dypdx;
import com.bci.pwtz.mysql.model.Dyxl;
import com.bci.pwtz.mysql.model.Pdbyq;
import com.bci.pwtz.mysql.model.Zsbyq;
import com.bci.pwtz.service.BusinessCommonService;
import com.bci.pwtz.service.DydlService;
import com.bci.pwtz.service.DydlfjxService;
import com.bci.pwtz.service.DygtService;
import com.bci.pwtz.service.DypdxService;
import com.bci.pwtz.service.DyxlService;
import com.bci.pwtz.service.PdbyqService;
import com.bci.pwtz.service.ZsbyqService;

@Controller
@RequestMapping("/user/dydl")
public class DydlController extends AbstractController
{
@Autowired
private DydlService service;
@Autowired
private DyxlService rService;
@Autowired
private DygtService objService;
@Autowired
private DydlfjxService dfService;
@Autowired
private DypdxService dpService;
@Autowired
private BusinessCommonService businessCommonService;
@Autowired
private PdbyqService pdService;
@Autowired
private ZsbyqService zsService;

@RequestMapping(value="/list",method=RequestMethod.POST)
@ResponseBody
public PaginationList<Dydl> list(String parentDeviceId,String deviceName,int pageSize,int pageNo){
    PaginationList<Dydl> list=new PaginationList<Dydl>();
    try
    {
        Long companyid=getLastCompanyId();
        list=service.findDydl(deviceName, companyid, 0, null, parentDeviceId, null, null, pageSize, pageNo);
        if(list!=null&&list.getTotalRecord()>0){
            for(Dydl d:list.getRecords()){
                int type=d.getStartdevicetype();
                if(type==4){
                    Dygt dt=objService.load(d.getStartdevicecode());
                    if(dt!=null)
                    d.setStartdevicecode(dt.getDevicename());
                }else if(type==16){
                    Dypdx dp=dpService.load(d.getStartdevicecode());
                    if(dp!=null)
                    d.setStartdevicecode(dp.getDevicename());
                }else if(type==17){
                    Dydlfjx df=dfService.load(d.getStartdevicecode());
                    if(df!=null)
                    d.setStartdevicecode(df.getDevicename());
                }else if(type==1){
                	Pdbyq pd=pdService.load(d.getStartdevicecode());
                	if(pd!=null)
                		d.setStartdevicecode(pd.getDevicename());                			
                }else if(type==2){
                	Zsbyq zs=zsService.load(d.getStartdevicecode());
                	if(zs!=null)
                		d.setStartdevicecode(zs.getDevicename());
                }
                type=d.getEnddevicetype();
                if(type==4){
                    Dygt dt=objService.load(d.getEnddevicecode());
                    if(dt!=null)
                    d.setEnddevicecode(dt.getDevicename());
                }else if(type==16){
                    Dypdx dp=dpService.load(d.getEnddevicecode());
                    if(dp!=null)
                    d.setEnddevicecode(dp.getDevicename());
                }else if(type==17){
                    Dydlfjx df=dfService.load(d.getEnddevicecode());
                    if(df!=null)
                    d.setEnddevicecode(df.getDevicename());
                }
                Dyxl obj=rService.load(d.getLinecode());
                d.setLinecode(obj.getDevicename());
            }
        }
    }
    catch (PwtzDatabaseException e)
    {
        e.printStackTrace();
    }
    return list;
}
@RequestMapping(value="/load",method=RequestMethod.POST)
@ResponseBody
public Dydl load(String deviceid){
    Dydl rtObj=new Dydl();
    try
    {
        if(deviceid!=null){
            rtObj=service.load(deviceid);
        }
    }
    catch (PwtzDatabaseException e)
    {
        e.printStackTrace();
    }
    return rtObj;
}

@RequestMapping(value="/dlist",method=RequestMethod.POST)
@ResponseBody
public List<Dydl> getDydl(Long companyId,String deviceid){
    List<Dydl> list=new ArrayList<Dydl>();
    PaginationList<Dydl> plist=new PaginationList<Dydl>();
    try
    {
        plist=service.findDydl(null, companyId, 1, null, deviceid, null, null, 0, 0);
        if(plist!=null&&plist.getTotalRecord()>0){
            list=plist.getRecords();
        }
    }
    catch (PwtzDatabaseException e)
    {
        e.printStackTrace();
    }
    return list;
}

@RequestMapping(value = "/edite", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> edite(String data)
{
    Map<String, String> map = new HashMap<String, String>();
    try
    {
        //data=java.net.URLDecoder.decode(data,"UTF-8");
        String [] list=decodeURL(data.split("&"));
        for(int i=0;i<list.length;i++){
            String[] array=list[i].split("=");
            if(array.length==1){
                map.put(array[0], "");
            }else{
                map.put(array[0], array[1]);
            }
        }
        int retCount = businessCommonService.getCountByDeviceName(getLastCompanyId(),(long)AbstractController.低压电缆, map.get("devicename"),map.get("deviceid"));
        if(retCount>0){
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "名称已存在！");
            return map;
        }
        CompanyUser user=(CompanyUser) session.getAttribute("user");
        Dydl device=new Dydl();
        device.setDeviceid(map.get("deviceid"));
        device.setDevicename(map.get("devicename"));
        device.setCommissioningdate(map.get("commissioningdate"));
        device.setCompanyid(user.getLastCompanyId());
        device.setCreateid(user.getCompanyUserId());
        device.setDevicenumber(map.get("devicenumber"));
        device.setEquipmentstate(map.get("equipmentstate"));
        device.setFactorydate(map.get("factorydate"));
        device.setLastoperatorid(user.getCompanyUserId());
        device.setLinecode(map.get("linecode"));
        device.setLocalcity(map.get("localcity"));
        device.setMaintenanceteam(map.get("maintenanceteam"));
        device.setModel(map.get("model"));
        device.setOperationstate(map.get("operationstate"));
        device.setOperationunit(map.get("operationunit"));
        device.setProductionfactory(map.get("productionfactory"));
        device.setSerialnumber(map.get("serialnumber"));
        device.setSyncstatus(0);
        device.setVoltagelevel(map.get("voltagelevel"));
        device.setCablesection(PwtzUtils.passDouble(map.get("cablesection")));
        device.setCorematerial(map.get("corematerial"));
        device.setCorenumber(map.get("corenumber"));
        device.setEnddevicetype(PwtzUtils.passInt(map.get("enddevicetype")));
        device.setEnddevicecode(map.get("enddevicecode"));
        device.setGiscode(map.get("giscode"));
        device.setInsulationtype(map.get("insulationtype"));
        device.setLength(PwtzUtils.passDouble(map.get("length")));
        device.setRatedloadflow(PwtzUtils.passDouble(map.get("ratedloadflow")));
        device.setRatedvoltage(map.get("ratedvoltage"));
        device.setStartdevicecode(map.get("startdevicecode"));
        device.setStartdevicetype(PwtzUtils.passInt(map.get("startdevicetype")));
        int ret = service.update(device);
        if (ret > 0)
        {
            setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.低压电缆, AbstractController.update, "修改低压电缆["+device.getDevicename()+"]成功", getUserId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "编辑低压电缆成功");
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "编辑低压电缆失败");
        }
    }
    catch (PwtzDatabaseException e)
    {
        map = packageException(e);
    }
    catch (UnsupportedEncodingException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return map;
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> add(String data)
{
    Map<String, String> map = new HashMap<String, String>();
    try
    {
        //data=java.net.URLDecoder.decode(data,"UTF-8");
        String [] list=decodeURL(data.split("&"));
        for(int i=0;i<list.length;i++){
            String[] array=list[i].split("=");
            if(array.length==1){
                map.put(array[0], "");
            }else{
                map.put(array[0], array[1]);
            }
        }
        int ret = businessCommonService.getCountByDeviceName(getLastCompanyId(),(long)AbstractController.低压电缆, map.get("devicename"));
        if(ret>0){
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "名称已存在！");
            return map;
        }
        CompanyUser user=(CompanyUser) session.getAttribute("user");
        Dydl device=new Dydl();
        UUID uuid=UUID.randomUUID();
        device.setDeviceid(uuid.toString());
        device.setDevicename(map.get("devicename"));
        device.setCommissioningdate(map.get("commissioningdate"));
        device.setCompanyid(user.getLastCompanyId());
        device.setCreateid(user.getCompanyUserId());
        device.setDevicenumber(map.get("devicenumber"));
        device.setEquipmentstate(map.get("equipmentstate"));
        device.setFactorydate(map.get("factorydate"));
        device.setLastoperatorid(user.getCompanyUserId());
        device.setLinecode(map.get("linecode"));
        device.setLocalcity(map.get("localcity"));
        device.setMaintenanceteam(map.get("maintenanceteam"));
        device.setModel(map.get("model"));
        device.setOperationstate(map.get("operationstate"));
        device.setOperationunit(map.get("operationunit"));
        device.setProductionfactory(map.get("productionfactory"));
        device.setSerialnumber(map.get("serialnumber"));
        device.setSyncstatus(0);
        device.setVoltagelevel(map.get("voltagelevel"));
        device.setCablesection(PwtzUtils.passDouble(map.get("cablesection")));
        device.setCorematerial(map.get("corematerial"));
        device.setCorenumber(map.get("corenumber"));
        device.setEnddevicetype(PwtzUtils.passInt(map.get("enddevicetype")));
        device.setEnddevicecode(map.get("enddevicecode"));
        device.setGiscode(map.get("giscode"));
        device.setInsulationtype(map.get("insulationtype"));
        device.setLength(PwtzUtils.passDouble(map.get("length")));
        device.setRatedloadflow(PwtzUtils.passDouble(map.get("ratedloadflow")));
        device.setRatedvoltage(map.get("ratedvoltage"));
        device.setStartdevicecode(map.get("startdevicecode"));
        device.setStartdevicetype(PwtzUtils.passInt(map.get("startdevicetype")));
        device = service.add(device);
        if (device !=null)
        {
            setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.低压电缆, AbstractController.update, "添加低压电缆["+device.getDevicename()+"]成功", getUserId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "添加低压电缆成功");
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "添加低压电缆失败");
        }
    }
    catch (PwtzDatabaseException e)
    {
        map = packageException(e);
    }
    catch (UnsupportedEncodingException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return map;
}
@RequestMapping(value="/delete",method=RequestMethod.POST)
@ResponseBody
public Map<String,String> delete(String deviceid){
    Map<String,String> map=new HashMap<String, String>();
    int result=0;
    try
    {
        Dydl device=service.load(deviceid);
        result=service.delete(deviceid);
        if (result>0&&device!=null)
        {
            setLog(device.getDeviceid(), device.getCompanyid(), AbstractController.低压电缆, AbstractController.delete, "删除低压电缆["+device.getDevicename()+"]成功", getUserId());
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "删除低压电缆成功");
        }
        else
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "删除低压电缆失败");
        }
    }
    catch (PwtzDatabaseException e)
    {
        map = packageException(e);
    }
    catch (CanNotDeleteException e)
    {
        map = packageException(e);
    }
    return map;
}
}